"use strict";

import Vue from 'vue';
import axios from "axios";
import store from '@/store/index.ts'
import router from '../router/index'
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

export const config = {
  baseURL: 'http://api.51coolplay.cc',

  //baseURL: "http://api.51coolplay.cc",
  timeout: 60 * 1000, // Timeout
  //withCredentials: true, // Check cross-site Access-Control
};


export const _axios = axios.create(config);


_axios.interceptors.request.use(
  function (config) {

    if (store.state.token)
      config.headers.Authorization = store.state.token
    // Do something before request is sent
    store.commit('openGlobalLoading')
    return config;
  },
  function (error) {
    store.commit('closeGlobalLoading')
    Vue.prototype.$notification.error({
      message: '加载错误',
      description: '' + error,
      placement: 'bottomRight',

    })
    // Do something with request error
    return Promise.reject(error);

  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {

    store.commit('closeGlobalLoading')
    // Do something with response data
    if (response.status != 200) {
      Vue.prototype.$notification.error({
        message: '加载错误',
        description: '错误码：' + response.status,
        placement: 'bottomRight'
      })
      return null
    }
    let res = response.data
    console.log(res)
    if (res.code < 0) {
      Vue.prototype.$notification.error({
        message: '加载错误',
        description: res.msg,
        placement: 'bottomRight'
      })
      if (res.code == -2) {
        router.push({ name: 'Login' })
      }
      return res
    }
    Vue.prototype.$notification.success({
      message: '加载成功',
      description: res.msg,
      placement: 'bottomRight',
    })
    return res;
  },
  function (error) {
    store.commit('closeGlobalLoading')
    Vue.prototype.$notification.error({
      message: '加载错误',
      description: '' + error,
      placement: 'bottomRight'
    })
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function (Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get () {
        return _axios;
      }
    },
    $axios: {
      get () {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;
